<template>
  <div v-loading="loading">
    <el-row
      :gutter="10"
      style="text-align: left;margin-top: 10px;"
    >
      <el-col :span="24">
        <el-button
          type="success"
          @click="buttonClicks.uploadExcelBtnClick"
        >
          读取excel
        </el-button>

        <input
          type="file"
          id="excelFileInput"
          style="display:none"
          accept=".xls,.xlsx"
          @change="buttonClicks.uploadExcelChanged"
        >
      </el-col>
    </el-row>

    <el-row
      :gutter="10"
      style="text-align: left;margin-top: 10px;"
    >
      <el-col :span="22">
        <el-input
          v-model="tableDatas.filters.svcodeStr"
          autosize
          type="textarea"
          placeholder="svcode"
        >
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button @click="buttonClicks.readInputClick">读取输入框</el-button>
      </el-col>
    </el-row>

    <el-row
      :gutter="10"
      style="text-align: left;margin-top: 10px;"
    >
      <el-col :span="24">
        <el-button
          type="primary"
          @click="buttonClicks.uploadBtnClick"
        >
          上传
        </el-button>
        <el-statistic
          :value="buttonClicks.currentCount"
          style="display: inline-block;"
        >
          <template #title>
            上传进度
          </template>
          <template #suffix>/{{ buttonClicks.uploadCount }}</template>
        </el-statistic>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <el-date-picker
              v-if="item.isDate"
              v-model="dialogDatas.currentData[item.value]"
              :type="item.dateOption ? item.dateOption.type : 'date'"
              :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
              :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
              :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
              :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
            />
            <el-switch
              v-else-if="item.isSwitch"
              v-model="dialogDatas.currentData[item.value]"
              inline-prompt
              active-text="启用"
              inactive-text="不启用"
              :active-value="item.trueValue"
              :inactive-value="item.falseValue"
            />
            <el-input
              v-else
              v-model="dialogDatas.currentData[item.value]"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-table
      class="marginTop10"
      :data="tableDatas.tableDatasAfterPage"
      stripe
      border
      empty-text="无数据"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
        show-overflow-tooltip
      >
        <template
          #default="scope"
          v-if="column.prop =='operate'"
        >
          <div>
            <el-button
              type="success"
              @click="tableDatas.editBtnClick(scope.row)"
            >修改</el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除该条记录?"
              @confirm="tableDatas.deleteBtnClick(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination>

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';

import myAxios from '@/myAxios/myAxios';
import { showWarning } from '@/hooks/useMyMessageBox';
import useMyXlsx from '@/hooks/useMyXlsx';
import myAxios28 from '@/myAxios/myAxios28';

export default {
  name: 'uploadZLMat',
  setup () {
    let loading = ref(false);

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = {};
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        {
          "value": "BADGE",
          "label": "BADGE",
          "isDate": false
        },
        {
          "value": "REPORTTOBADGE",
          "label": "REPORTTOBADGE",
          "isDate": false
        },
        {
          "value": "DATE_TIME",
          "label": "精确到秒的时间(示例,可删除)",
          "isDate": true,
          "dateOption": {
            "type": "datetime",
            "format": "YYYY/MM/DD HH:mm:ss",
            "dateFormat": "YYYY/MM/DD",
            "timeFormat": "HH:mm:ss",
            "valueFormat": "YYYY/MM/DD HH:mm:ss"
          }
        }
      ],
      confirmBtnClick: function () {
        loading.value = true;

        let params = `${dialogDatas.currentData.BADGE}`
          + `\t${dialogDatas.currentData.REPORTTOBADGE}`;
        myAxios.post('添加或更新', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!' + res
            });
            getTableDatas();
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = function () {
      loading.value = true;

      let params = ``;
      myAxios.get('获取数据', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          tableDatas.oritableData = [...res];
          ElMessage({
            showClose: true,
            type: 'success',
            message: '最新数据获取成功!'
          });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      // getTableDatas();
    });

    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {
        svcodeStr: '',

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;
        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        {
          "prop": "SVCODE",
          "label": "SVCODE",
          "align": "center",
          "width": 170,
        },
        {
          "prop": "UPLOAD_STATE",
          "label": "上传状态",
          "align": "center",
          "width": 170,
        },
        {
          "prop": "ABANDON_STATE",
          "label": "废弃状态",
          "align": "center",
          "width": 170,
        },
        {
          "prop": "UPLOAD_JSON",
          "label": "上传内容",
          "align": "center",
        },

      ],
      oritableData: [
      ],
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;

        let params = ``;
        myAxios.post('删除', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '删除成功!' + res
            });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
    });

    let buttonClicks = reactive({
      uploadCount: 0,
      currentCount: 0,
      upload_loading: false,

      readInputClick: function () {
        if (buttonClicks.upload_loading) {
          showWarning('正在上传中,请勿重复点击!');
          return;
        }
        let inputCodes = tableDatas.filters.svcodeStr.trim().split(',');
        let datas = inputCodes.map(item => {
          return {
            SVCODE: item,
            UPLOAD_STATE: '未上传',
            ABANDON_STATE: '未上传',
            UPLOAD_JSON: '[]',
          };
        });
        buttonClicks.currentCount = 0;
        buttonClicks.uploadCount = datas.length;
        tableDatas.oritableData = [...datas];
      },
      uploadBtnClick: function () {
        if (buttonClicks.upload_loading) {
          showWarning('正在上传中,请勿重复点击!');
          return;
        }
        ElMessageBox.confirm(
          '即将上传数据,是否继续?',
          '上传确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          buttonClicks.uploadExcelDatas();
        }).catch(() => {
          showWarning('已取消');
        });
      },

      uploadExcelBtnClick: function () {
        if (buttonClicks.upload_loading) {
          showWarning('正在上传中,请勿重复点击!');
          return;
        }
        document.querySelector('#excelFileInput').click();
      },
      uploadExcelChanged: async function ({ srcElement }) {
        if (srcElement.files.length) {
          let xlsx = useMyXlsx();
          let excelDatas = await xlsx.getDataFromExcel(srcElement.files[0]);
          let requestParamsArr = [];
          console.log('excelDatas :>> ', excelDatas);
          let tableUIDatas = {
            tableDatas: excelDatas[0].map(item => {
              return {
                SVCODE: item['SVCODE'],
                UPLOAD_STATE: '未上传',
                ABANDON_STATE: '未上传',
                UPLOAD_JSON: '[]',
              };
            }),
            columns: Object.keys(excelDatas[0][0]).map(key => {
              return {
                key: key,
                title: key,
                dataKey: key,
                align: 'center',
                width: 100,
              };
            })
          };
          tableDatas.filters.svcodeStr = excelDatas[0].map(item => item['SVCODE']).join(',');
          tableDatas.oritableData = [...tableUIDatas.tableDatas];
          buttonClicks.uploadCount = tableUIDatas.tableDatas.length;
          console.log('tableUIDatas :>> ', tableUIDatas);
          // dataTableDialog.value.showTableDialog('Excel数据', tableUIDatas);
          document.getElementById("excelFileInput").value = null;
        }
      },
      uploadExcelDatas: async function () {
        let excelDatas = tableDatas.filters.svcodeStr.trim().split(',');
        buttonClicks.upload_loading = true;
        buttonClicks.currentCount = 0;
        buttonClicks.uploadCount = excelDatas.length;
        for (let i = 0; i < excelDatas.length; i++) {
          let item = excelDatas[i];
          let requestObj = {
            "zlCodes": item,
          };

          let result = await myAxios28.post('zlMachine/uploadByZLcode', JSON.stringify(requestObj));
          let datas = tableDatas.oritableData.filter(el => el.SVCODE == item);
          if (datas.length) {
            if (result.returnData.status == 200) {
              datas[0].UPLOAD_JSON = result.returnData.uploadJson;
              datas[0].UPLOAD_STATE = '成功';
              //  console.log('result.returnData.uploadJson :>> ', result.returnData.uploadJson);
              let contentData = JSON.parse(result.returnData.uploadJson);
              datas[0].ABANDON_STATE = contentData[0].state == 0 ? '已废弃' : '未废弃';
            }
            else if (result.returnData.status != 200) {
              let errMsg = '上传失败,' + result.returnData.message;
              datas[0].UPLOAD_JSON = result.returnData.uploadJson;
              datas[0].UPLOAD_STATE = errMsg;
              datas[0].ABANDON_STATE = errMsg;
            }
          }
          buttonClicks.currentCount = i + 1;
          console.log('buttonClicks.currentCount :>> ', buttonClicks.currentCount);
        }
        buttonClicks.upload_loading = false;
      },
    });

    return {
      loading,
      dialogDatas,
      tableDatas,
      buttonClicks,
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

